package com.roger.uia;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiCollection;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.util.Log;

import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.UiWatch;
import com.roger.uia.helper.manager.Package;
import com.roger.uia.helper.manager.Wifi;
import com.roger.uia.helper.util.FileUtils;
import com.roger.uia.helper.util.StrUtils;
import com.roger.uia.helper.UiCom;
import com.roger.uia.helper.util.ZipUtils;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.roger.uia.helper.UiBase.filePath;
import static com.roger.uia.helper.UiBase.mDevice;
import static com.roger.uia.helper.UiBase.waitTime;

@SuppressWarnings("ConstantConditions")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestWifiUser {
    private static final String TAG = TestWifiUser.class.getSimpleName();
    private WifiManager wifiManager = (WifiManager) InstrumentationRegistry.getTargetContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    private ConnectivityManager connManager = (ConnectivityManager) InstrumentationRegistry.getTargetContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    private String[] wifiList;
    private Date timeMUnConn; //断开重连时间点
    private String baiDuP,routerP;
    private Boolean isMonitor=true;//监控线程是否继续
    private int unConnTimes = 0;//断连总次数
    private int connFlag = 0;//连接标志，是否为断开重连
    private int unConnFlag = 0;//断开标志，是否不为刚断开
    private int errorFlag = 0;//本轮测试异常标志
    private String tencent,douyin,douyu,weibo,internet,download,apk_address;
    private int tencent_play_time,douyin_play_time,douyu_play_time,weibo_play_time,internet_search_time,refresh_gap;
    private static ArrayList<cases> testCase = new ArrayList<>();//测试列表

    @BeforeClass
    public static void beforeClass() throws Throwable {
        if(!mDevice.isScreenOn()) mDevice.wakeUp();
        mDevice.pressHome();
    }

    @Before
    public void setUp()  {
        Log.d(TAG,"-- set up --");
        Package.pac().grantAllPerms(InstrumentationRegistry.getTargetContext().getPackageName());
        UiCom.setScreenOn();
        UiWatch.getWatcher().runErrorWatcher();
        UiWatch.getWatcher().runSpecialWatcher();
        UiMonitor();
    }

    @After
    public void tearDown() {
        Log.d(TAG,"-- tear down --");
        UiWatch.getWatcher().removeErrorWatcher();
        UiWatch.getWatcher().removeSpecialWatcher();
    }

    @AfterClass
    public static void afterClass() throws Throwable {
        mDevice.pressHome();
//      打开com.roger.wificfg apk,显示测试完成
        mDevice.executeShellCommand("am start -a android.intent.action.MAIN -n com.roger.wificfg/com.roger.wificfg.MainActivity --ei pid 0");
        UiBase.waitObjCheck(UiBase.objSelect[0], "CONNECT REPORT", 10);
        mDevice.executeShellCommand("am broadcast -a com.roger.wificfg.OPEN_URL --es url end");
    }

    @Test
    public void UserTest_checkWifi(){
//        获取设备名称，例：LenovoTB-J606L
        String product = Build.PRODUCT;
        String logPath = logPath(product);
//       获取外置sd卡路径 getSecondaryStoragePath()在Q版本失效
        String secondaryPath = FileUtils.getSecondaryStoragePath();
//        获取casesRandom的值为true or false
        String casesRandom = getOtherCfg(filePath + "testWifi/config/other.cfg", "casesRandom:");
//        获取运行的次数
        int testTimes =Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","times:"));
        getWifiCfg(filePath+"testWifi/config/wifi.cfg");
        getOtherCfg();
        addTestCase();
//        将 String[] 转为List[]
        List list = Arrays.asList(wifiList);
        for (int t=0;t<testTimes;t++){
            Collections.shuffle(list);
            for(int i=0;i<list.size();i++){
                String[] wifiInfo =  ((String) list.get(i)).split("<->");
                String isSearchable = wifiInfo[0];
                String wifiName = wifiInfo[1];
                String wifiPwd = wifiInfo[2];
                String security = wifiInfo[3];
                String routerIP = wifiInfo[4];
                String reportName = wifiName.replaceAll(" ","");
                if(!FileUtils.existFile(filePath+"testWifi/result/"+reportName+".csv")){
                    FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv","DateTime,ConnState,UpRates,DownRates,RSSI,PingBaiDu,PingRouter,UnConnTimes,UnConnAllTime(s),");
                }
                UiObject menuText = mDevice.findObject(new UiSelector().textMatches(wifiName));
                UiObject menuTextAdd = mDevice.findObject(new UiSelector().textMatches("(?i)Add network|添加网络"));
                String success="(?i)"+wifiName+",Connected.*|"+wifiName+",已连接.*";
                UiScrollable secMenuList;
                if (Build.VERSION.SDK_INT >= 29 )
                    secMenuList= new UiScrollable(new UiSelector().resourceId(StrUtils.recycler));
                else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    secMenuList = new UiScrollable(new UiSelector().resourceId(StrUtils.settingList));
                else
                    secMenuList = new UiScrollable(new UiSelector().resourceId("android:id/list"));
                try {
                    removeWifiSaved();
                    Log.d(TAG, "connect wifi :" + wifiName);
//                    打开WIFI
                    enterWLAN();
                    switch (isSearchable) {
//                        能够在WIFI 界面显示的
                        case "true":
                            for (int j = 0; j < 3; j++) {
                                secMenuList.scrollIntoView(menuText);
                                if (menuText.exists()) {
                                    menuText.clickAndWaitForNewWindow();
                                    break;
                                }
                            }
                            if (!wifiPwd.equals("null")) {
                                UiBase.waitObjCheck(UiBase.objSelect[3], StrUtils.password, 5);
                                UiBase.inputTxtToObj(UiBase.objSelect[3], StrUtils.password, wifiPwd);
                                UiBase.waitClickObj(UiBase.objSelect[2], StrUtils.connect, 10);
                            }
                            UiBase.waitObjCheck(UiBase.objSelect[6],success,30);
                            break;
//                            在WIFI 界面不能显示,需要手动添加
                        case "false":
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                for (int j = 0; j < 3 ;j++){
                                    secMenuList.scrollIntoView(menuTextAdd);
                                    if(menuTextAdd.exists()) {
                                        menuTextAdd.clickAndWaitForNewWindow();
                                        break;
                                    }
                                }
                            }else{
                                mDevice.pressMenu();
                                UiBase.waitClickObj(UiBase.objSelect[2],"(?i)Add network|添加网络",3);
                            }
                            UiBase.waitObj(UiBase.objSelect[3],"com.android.settings:id/ssid",3);
                            UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/ssid",wifiName);
                            if(!wifiPwd.equals("null")){
                                UiBase.clickObj(UiBase.objSelect[3],"com.android.settings:id/security");
                                UiBase.waitClickObj(UiBase.objSelect[0],security,5);
                                UiBase.waitObj(UiBase.objSelect[3],"com.android.settings:id/password",3);
                                UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/password",wifiPwd);
                            }
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                                UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[3],"com.android.settings:id/wifi_advanced_togglebox");
                                UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[3],"com.android.settings:id/hidden_settings");
                                UiBase.waitClickObj(UiBase.objSelect[2],"Yes|是",3);
                            }

                            UiBase.waitClickObj(UiBase.objSelect[2],"SAVE|保存",3);
                            mDevice.pressHome();
                            enterWLAN();
                            UiBase.waitObjCheck(UiBase.objSelect[6],success,30);
                            break;
                        default:
                            for (int j = 0; j < 3; j++) {
                                secMenuList.scrollIntoView(menuText);
                                if (menuText.exists()) {
                                    menuText.clickAndWaitForNewWindow();
                                    break;
                                }
                            }
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                UiBase.waitClickObj(UiBase.objSelect[3],"com.android.settings:id/ca_cert",3);
                                UiBase.waitClickObj(UiBase.objSelect[2],"(?i)allow|不验证|Do not validate",3);
                                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                                    UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[3],StrUtils.identity);
                                    UiBase.inputTxtToObj(UiBase.objSelect[3],StrUtils.identity,wifiPwd);
                                    UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[3],StrUtils.password);
                                }else {
                                    UiBase.scrollReidClickObj("android:id/customPanel",UiBase.objSelect[3],StrUtils.identity);
                                    UiBase.inputTxtToObj(UiBase.objSelect[3],StrUtils.identity,wifiPwd);
                                    UiBase.scrollReidClickObj("android:id/customPanel",UiBase.objSelect[3],StrUtils.password);
                                }
                            }else{
                                UiBase.waitObj(UiBase.objSelect[3],"com.android.settings:id/l_ca_cert",3);
                                UiBase.scrollReidClickObj("com.android.settings:id/security_fields",UiBase.objSelect[3],StrUtils.identity);
                                UiBase.inputTxtToObj(UiBase.objSelect[3],StrUtils.identity,wifiPwd);
                                UiBase.scrollReidClickObj("com.android.settings:id/security_fields",UiBase.objSelect[3],StrUtils.password);
                            }
                            UiBase.inputTxtToObj(UiBase.objSelect[3],StrUtils.password,security);
                            UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.connect,3);
                            UiBase.waitObjCheck(UiBase.objSelect[6],success,30);
                            break;
                    }
                    changePrivacy(wifiName);
                    //start test
                    try{
                        logOn(product,true);
                        String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
                        FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",timeMS+",connect success");
                        if(casesRandom.equals("true")) Collections.shuffle(testCase);
                        connFlag=0;
                        wifiMonitor(reportName,wifiName,routerIP);
                        for(int m=0;m<testCase.size();m++){
                            testCase.get(m).run(wifiName);
                            if(errorFlag==1){
                                Log.d(TAG,"disconnect has happened,skip next tests");
                                break;
                            }
                        }
                    }catch (Throwable e){
                        Log.d(TAG,"error with test");
                    }finally {
                        isMonitor=false;
                        logOn(product,false);
                        if(secondaryPath == null){
                            Log.d(TAG,"no secondary sdcard");
                            if(FileUtils.existFile(logPath)) {
                                try{
                                    if(errorFlag==1) {
                                        Log.d(TAG,"disconnect happen,start zip logs");
                                        String logTime = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
                                        ZipUtils.zip().zipFile(logPath, filePath+"logs_"+ logTime + ".zip");
                                        Log.d(TAG,"zip logs end");
                                    }else Log.d(TAG,"no disconnect happen,start clear logs");
                                    mDevice.executeShellCommand("rm -rf "+ logPath);
                                }catch (Throwable e){
                                    Log.d(TAG,"copy logs fail");
                                    e.printStackTrace();
                                }
                            }
                        }else{
                            Log.d(TAG,"exist secondary sdcard");
                            File f = new File(secondaryPath);
                            long usableSpace = f.getUsableSpace()/1024/1024/1024;
                            if(usableSpace>5 && FileUtils.existFile(logPath)){
                                try{
                                    if(errorFlag==1) {
                                        Log.d(TAG,"usable Space:"+usableSpace+"G,copy logs to secondary sdcard now");
                                        String timeLog = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
                                        mDevice.executeShellCommand("cp -r "+ logPath + " " + secondaryPath +"/logs_"+timeLog);
                                        Log.d(TAG,"copy logs to secondary sdcard end");
                                    }else  Log.d(TAG,"no disconnect happen,start clear logs");
                                    mDevice.executeShellCommand("rm -rf "+ logPath);
                                }catch (Throwable e){
                                    Log.d(TAG,"copy logs fail");
                                    e.printStackTrace();
                                }
                            }else{
                                Log.d(TAG,"usable Space less than 5G or mtklog not exist!");
                            }
                        }
                        mDevice.pressHome();
                        errorFlag=0;
                    }
                }catch (Throwable e){
                    String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
                    FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",timeMS+",connect fail");
                    Log.d(TAG,"connect wifi fail");
                    e.printStackTrace();
                }
            }
        }
    }

    private static void MLogOn(boolean b){
        if(!UiBase.existObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton")){
            try{
                mDevice.executeShellCommand("am start -n com.mediatek.mtklogger/com.mediatek.mtklogger.MainActivity");
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        try{
            UiBase.waitObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton",5);
            if(b){
                if(!UiBase.objChecked(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton")) {
                    UiBase.clickObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton");
                    UiBase.waitClickIfObjExist(UiBase.objSelect[3], "android:id/button1",3);
                }
            }else{
                if(UiBase.objChecked(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton")) {
                    UiBase.clickObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton");
                    UiBase.waitClickIfObjExist(UiBase.objSelect[3], "android:id/button1",3);
                }
            }
            SystemClock.sleep(waitTime * 10);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    private static void MLogOn1(boolean b){
        String reid = "com.debug.loggerui:id/startStopToggleButton";
        if(!UiBase.existObj(UiBase.objSelect[3], reid)){
            try{
                mDevice.executeShellCommand("am start -n com.debug.loggerui/com.debug.loggerui.MainActivity");
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        try{
            UiBase.waitObj(UiBase.objSelect[3], reid,5);
            if(b){
                if(!UiBase.objChecked(UiBase.objSelect[3], reid)) {
                    UiBase.clickObj(UiBase.objSelect[3], reid);
                    UiBase.waitClickIfObjExist(UiBase.objSelect[3], "android:id/button1",3);
                }
            }else{
                if(UiBase.objChecked(UiBase.objSelect[3], reid)) {
                    UiBase.clickObj(UiBase.objSelect[3], reid);
                    UiBase.waitClickIfObjExist(UiBase.objSelect[3], "android:id/button1",3);
                }
            }
            SystemClock.sleep(waitTime * 10);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    private static void QLogOn0(boolean b){
        if (!UiBase.existObj(UiBase.objSelect[3], "com.wingtech.logcat:id/actionbar_title")){
            try{
                mDevice.executeShellCommand("am start -n com.wingtech.logcat/com.wingtech.logcat.LogcatHomeActivity");
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        try{
            UiBase.waitClickObj(UiBase.objSelect[2], "AP Log|AP日志",10);
            UiBase.waitObjCheck(UiBase.objSelect[3],"com.wingtech.logcat:id/log_switch",3);
            if(b){
                if(!UiBase.objChecked(UiBase.objSelect[3],"com.wingtech.logcat:id/log_switch")) {
                    UiBase.clickObj(UiBase.objSelect[3],"com.wingtech.logcat:id/log_switch");
                }
            }else{
                if(UiBase.objChecked(UiBase.objSelect[3],"com.wingtech.logcat:id/log_switch")) {
                    UiBase.clickObj(UiBase.objSelect[3],"com.wingtech.logcat:id/log_switch");
                }
            }
            SystemClock.sleep(waitTime * 5);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    private static void QLogOn1(boolean b){
        if (!UiBase.existObj(UiBase.objSelect[2], "APLog|AP日志")){
            try{
                UiBase.openApp("com.android.contacts");
                UiBase.waitClickObj(UiBase.objSelect[3],"com.android.contacts:id/menu_search",10);
                UiBase.waitObj(UiBase.objSelect[3],"com.android.contacts:id/search_view",10);
                UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.contacts:id/search_view","####3333#");
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        try{
            UiBase.waitObjCheck(UiBase.objSelect[2], "APLog|AP日志",10);
            UiCollection list = new UiCollection(new UiSelector().resourceId("android:id/list"));
            UiObject apLog = UiBase.getObjSameLine(list,mDevice.findObject(new UiSelector().className("android.widget.LinearLayout").index(3)),UiBase.getObj(UiBase.objSelect[3],"android:id/switch_widget"));
            UiObject tcpLog = UiBase.getObjSameLine(list,mDevice.findObject(new UiSelector().className("android.widget.LinearLayout").index(4)),UiBase.getObj(UiBase.objSelect[3],"android:id/switch_widget"));
            if(b){
                if(!apLog.isChecked()) {
                    apLog.clickAndWaitForNewWindow();
                    UiBase.waitClickObj(UiBase.objSelect[3],"android:id/button1",3);
                }
                if(!tcpLog.isChecked()) tcpLog.clickAndWaitForNewWindow();
            }else{
                if(apLog.isChecked()) {
                    apLog.clickAndWaitForNewWindow();
                    UiBase.waitClickObj(UiBase.objSelect[3],"android:id/button1",3);
                }
                if(tcpLog.isChecked()) tcpLog.clickAndWaitForNewWindow();
            }
            SystemClock.sleep(waitTime * 5);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    private static void QLogOn2(boolean b){
        if (!UiBase.existObj(UiBase.objSelect[2], "Tcard log|T卡log")){
            try{
                UiBase.openApp("com.android.contacts");
                UiBase.waitClickObj(UiBase.objSelect[3],"com.android.contacts:id/menu_search",10);
                UiBase.waitObj(UiBase.objSelect[3],"com.android.contacts:id/search_view",3);
                UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.contacts:id/search_view","####3333#");
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"确定",5);
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        try{
            if(b){
                UiBase.waitClickObj(UiBase.objSelect[2],"methods two|方法二",3);
            }else{
                UiBase.waitClickObj(UiBase.objSelect[2],"Exit|退出",3);
            }
            SystemClock.sleep(waitTime * 5);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    private static void QLogOn3(boolean b){
        if (!UiBase.existObj(UiBase.objSelect[2], "LenovoLogger")){
            try{
                UiBase.openApp("com.android.contacts");
                UiBase.waitClickObj(UiBase.objSelect[3],"com.android.contacts:id/menu_search",10);
                UiBase.waitObj(UiBase.objSelect[3],"com.android.contacts:id/search_view",3);
                UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.contacts:id/search_view","####3333#");
                UiBase.waitObj(UiBase.objSelect[2],"Warnning",5);
                if(UiBase.existObj(UiBase.objSelect[2],"Warnning")) mDevice.pressBack();
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        try{
            if(b){
                if(UiBase.objEnabled(UiBase.objSelect[2],"Main log"))
                    UiBase.waitClickObj(UiBase.objSelect[3],"com.lenovo.loggerpannel:id/start",3);
            }else{
                if(!UiBase.objEnabled(UiBase.objSelect[2],"Main log")){
                    UiBase.waitClickObj(UiBase.objSelect[3],"com.lenovo.loggerpannel:id/start",3);
                    UiBase.waitObjGone(UiBase.objSelect[2],"Stop recording and save|停止记录并保存",600);
                }
            }
            SystemClock.sleep(waitTime * 5);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    private String logPath(String product){
        switch (product) {
            case "LenovoPB-6505Y":
                return filePath +"wt_logs";
            case "YT3-850L":
            case "LenovoTB-X605L":
                return filePath +"log";
            case "LAVIETabE10FHD1": case "LenovoTB-X605LCV":
            case "LenovoTB-X605FC":
                return filePath +"logs";
            case "LenovoTB-X306F_EEA": case "LenovoTB-X306F":
                return filePath +"debuglogger";
            default:
                return filePath +"mtklog";
        }
    }

    private void logOn(String product,boolean b){
        switch (product) {
            case "LenovoPB-6505Y":
                QLogOn0(b);
                break;
            case "LAVIETabE10FHD1": case "LenovoTB-X605LCV":
            case "LenovoTB-X605FC":
                QLogOn1(b);
                break;
            case "YT3-850L":
                QLogOn2(b);
                break;
            case "LenovoTB-X605L":
                QLogOn3(b);
                break;
            case "LenovoTB-X306F_EEA":case "LenovoTB-X306F":
                MLogOn1(b);
                break;
            default:
                MLogOn(b);
                break;
        }
    }

    //进入wifi搜索界面
    private void enterWLAN() throws Throwable {
//        判断WIFI是否处于开启状态
        if (UiBase.existObj(UiBase.objSelect[2], StrUtils.wifi) && UiBase.existObj(UiBase.objSelect[3], StrUtils.frictionIcon)) {
            SystemClock.sleep(waitTime);
        } else {
            mDevice.pressHome();
            UiBase.openApp(StrUtils.settingPac);

            if (Build.VERSION.SDK_INT >= 29) {
                UiBase.waitObj(UiBase.objSelect[3], StrUtils.settingScroll, 10);
                UiBase.scrollReidClickObj(StrUtils.settingScroll, UiBase.objSelect[2], StrUtils.settingNetwork);
                UiBase.waitClickObj(UiBase.objSelect[2], StrUtils.wifi, 5);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                UiBase.waitObj(UiBase.objSelect[3], StrUtils.settingDashBoard, 10);
                UiBase.scrollReidClickObj(StrUtils.settingDashBoard, UiBase.objSelect[2], StrUtils.settingNetwork);
                UiBase.waitClickObj(UiBase.objSelect[2], StrUtils.wifi, 5);
            } else {
                UiBase.waitObj(UiBase.objSelect[3], StrUtils.settingDashBoard, 10);
                UiBase.scrollReidClickObj(StrUtils.settingDashBoard, UiBase.objSelect[2], StrUtils.wifi);
            }

            UiBase.waitObj(UiBase.objSelect[3], StrUtils.switch_widget, 5);
//            判断是否打开WIFI
            if (UiBase.getTxtFromObj(UiBase.objSelect[3], StrUtils.switch_widget).matches(StrUtils.off)) {
                UiBase.clickObj(UiBase.objSelect[3], StrUtils.switch_widget);
                SystemClock.sleep(waitTime * 10);
            }
            SystemClock.sleep(waitTime);
        }
    }

    //移除已保存的wifi
    private void removeWifiSaved(){
        try{
            WifiManager wifiManager = (WifiManager) InstrumentationRegistry.getTargetContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();
            if(!String.valueOf(wifiConfigs).equals("[]")){
                enterWLAN();
                UiScrollable secMenuList = new UiScrollable(new UiSelector().resourceId(StrUtils.settingList));
                UiScrollable secMenuListX = new UiScrollable(new UiSelector().resourceId(StrUtils.recycler));
                for(int j=0;j<3;j++){
                    if(Build.VERSION.SDK_INT >= 29)
                        secMenuListX.scrollIntoView(UiBase.getObj(UiBase.objSelect[2],StrUtils.savedWifi));
                    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                        secMenuList.scrollIntoView(UiBase.getObj(UiBase.objSelect[2],StrUtils.savedWifi));
                    else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        UiBase.clickObj(UiBase.objSelect[6],"(?i)Configure|配置");
                    else
                        mDevice.pressMenu();

//                    判断已保存WIFI是否存在
                    if(UiBase.existObj(UiBase.objSelect[2],StrUtils.savedWifi)) {
                        UiBase.clickObj(UiBase.objSelect[2],StrUtils.savedWifi);
                        for (WifiConfiguration wifiConfig : wifiConfigs) {
                            String name = String.valueOf(wifiConfig.SSID.replaceAll("\"",""));
                            Log.d(TAG,"remove wifi : "+ name);
                            if (UiBase.existObj(UiBase.objSelect[0],name)){
                                UiBase.clickObj(UiBase.objSelect[0],name);
                                UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.forget,3);
                            }
                        }
                        break;
                    }else {
                        Log.d(TAG,"find saved wifi fail");
                    }
                }
            }else{
                Log.d(TAG,"no saved wifi");
            }
        }catch (Throwable e){
            Log.d(TAG,"remove saved wifi fail");
            e.printStackTrace();
        }finally {
            mDevice.pressBack();
        }
    }

    //解析wifi配置文件
    private void getWifiCfg(String path){
        try {
            File file = new File(path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                if(!line.startsWith("#")){
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            }
            wifiList=stringBuilder.toString().split("\n");
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //解析其他配置信息
    private String getOtherCfg(String path,String startTag){
        String s ="";
        try {
            File file = new File(path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                if(line.startsWith(startTag)){
                    stringBuilder.append(line);
                }
            }
            s = stringBuilder.toString().replaceAll(startTag,"").replaceAll(" ","");
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return s;
    }

    private void getOtherCfg(){
//        获取other.cfg 中需要运行APP及运行时间的值
        tencent = getOtherCfg(filePath+"testWifi/config/other.cfg","tencent:");
        tencent_play_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","tencent_play_time:"));
        douyin = getOtherCfg(filePath+"testWifi/config/other.cfg","douyin:");
        douyin_play_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","douyin_play_time:"));
        douyu = getOtherCfg(filePath+"testWifi/config/other.cfg","douyu:");
        douyu_play_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","douyu_play_time:"));
        weibo = getOtherCfg(filePath+"testWifi/config/other.cfg","weibo:");
        weibo_play_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","weibo_play_time:"));
        internet = getOtherCfg(filePath+"testWifi/config/other.cfg","internet:");
        internet_search_time =60*Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","internet_search_time:"));
        download = getOtherCfg(filePath+"testWifi/config/other.cfg","download:");
        apk_address = getOtherCfg(filePath+"testWifi/config/other.cfg","apk_address:");
        refresh_gap = Integer.parseInt(getOtherCfg(filePath+"testWifi/config/other.cfg","refresh_gap:"));
        if (refresh_gap==0) refresh_gap=(int)(5+16*Math.random());
    }

    private void playTencentVideo(int timeTest,String wifiName){
        mDevice.pressHome();
        try {
            String content = getOtherCfg(filePath+"testWifi/config/other.cfg","tencent_content:");
            UiBase.forceStopApp("com.tencent.qqlive");
            UiBase.openApp("com.tencent.qqlive");
            UiBase.waitClickIfObjExist(UiBase.objSelect[2],"同意",5);
            UiBase.waitClickIfObjExist(UiBase.objSelect[2],"我知道了",5);
            UiBase.waitClickObj(UiBase.objSelect[3],"com.tencent.qqlive:id/a8y",3);
            UiBase.waitObj(UiBase.objSelect[3],"com.tencent.qqlive:id/yh",3);
            UiBase.inputTxtToObj(UiBase.objSelect[3],"com.tencent.qqlive:id/yh",content);
            UiBase.waitClickObj(UiBase.objSelect[2],"搜索",3);
            UiBase.waitClickObj(UiBase.objSelect[2],"立即播放",10);
            UiBase.waitObjCheck(UiBase.objSelect[3],"com.tencent.qqlive:id/byn",5);
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play tencent video start");
            Log.d(TAG,"start play tencent video");
            SystemClock.sleep(waitTime * timeTest);
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play tencent video fail");
            Log.d(TAG,"play tencent video fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.tencent.qqlive");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void playDouyin(int timeGap,int timeTest,String wifiName){
        mDevice.pressHome();
        try{
            UiBase.forceStopApp("com.ss.android.ugc.aweme");
            UiBase.openApp("com.ss.android.ugc.aweme");
            UiBase.waitObjCheck(UiBase.objSelect[0],"首页",10);
            int count=0;
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play douyin start");
            Log.d(TAG,"start play douyin video");
            while(count < timeTest/timeGap) {
                SystemClock.sleep(waitTime * timeGap);
                mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H / 2, StrUtils.SCREEN_W / 2, 10, 100);
                count++;
            }
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play douyin fail");
            Log.d(TAG,"play douyin fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.ss.android.ugc.aweme");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void playDouyu(int timeTest,String wifiName){
        mDevice.pressHome();
        try{
            String zhubo = getOtherCfg(filePath+"testWifi/config/other.cfg","douyu_zhubo:");
            String content = getOtherCfg(filePath+"testWifi/config/other.cfg","douyu_content:");
            UiBase.forceStopApp("air.tv.douyu.android");
            UiBase.openApp("air.tv.douyu.android");
            //检测更新
            UiBase.waitClickIfObjExist(UiBase.objSelect[3],"air.tv.douyu.android:id/b2k",10);
            //查询历史记录并播放
            UiBase.waitClickObj(UiBase.objSelect[3],"air.tv.douyu.android:id/cj6",3);
            UiBase.waitClickObj(UiBase.objSelect[3],"air.tv.douyu.android:id/cpc",3);
            UiBase.inputTxtToObj(UiBase.objSelect[3],"air.tv.douyu.android:id/cpc",zhubo);
            mDevice.pressEnter();
            UiBase.waitClickObj(UiBase.objSelect[1],content,10);
            UiBase.waitClickIfObjExist(UiBase.objSelect[3],"air.tv.douyu.android:id/atk",10);
            UiBase.waitObjCheck(UiBase.objSelect[0],"聊天",10);
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play douyu start");
            Log.d(TAG,"start play douyu video");
            SystemClock.sleep(waitTime * timeTest);
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play douyu fail");
            Log.d(TAG,"play douyu fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("air.tv.douyu.android");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void playWeibo(int timeGap,int timeTest,String wifiName){
        mDevice.pressHome();
        try{
            UiBase.forceStopApp("com.sina.weibo");
            UiBase.openApp("com.sina.weibo");
            UiBase.waitClickIfObjExist(UiBase.objSelect[3],"com.sina.weibo:id/tv_title_lookaround",10);
            UiBase.waitClickIfObjExist(UiBase.objSelect[3],"com.sina.weibo:id/tv_title_lookaround",5);
            UiBase.waitClickObj(UiBase.objSelect[6],"Discover|发现",5);
            UiBase.waitObjCheck(UiBase.objSelect[3],"com.sina.weibo:id/tv_search_keyword",3);
            mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H /2, StrUtils.SCREEN_W / 2,10, 100);
            mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H /2, StrUtils.SCREEN_W / 2,10, 100);
            int count=0;
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play weibo start");
            Log.d(TAG,"start play weibo");
            while(count < timeTest/timeGap) {
                SystemClock.sleep(waitTime * timeGap);
                mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H / 2, StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H - 10, 100);
                count++;
            }
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",play weibo fail");
            Log.d(TAG,"play weibo fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.sina.weibo");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void searchInternet(int timeGap,int timeTest,String wifiName){
        mDevice.pressHome();
        try {
            String content = getOtherCfg(filePath+"testWifi/config/other.cfg","internet_address:");
            UiBase.forceStopApp("com.roger.wificfg");
            mDevice.executeShellCommand("am start -a android.intent.action.MAIN -n com.roger.wificfg/com.roger.wificfg.MainActivity --ei pid 0");
            UiBase.waitObjCheck(UiBase.objSelect[0],"CONNECT REPORT",10);
            mDevice.executeShellCommand("am broadcast -a com.roger.wificfg.OPEN_URL --es url "+ content);
            UiBase.waitObjCheck(UiBase.objSelect[0],"百度一下,你就知道",10);
            SystemClock.sleep(waitTime*timeGap);
            int count=0;
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",search internet start");
            Log.d(TAG,"start search the internet");
            while(count < timeTest/timeGap) {
                SystemClock.sleep(waitTime * timeGap);
                mDevice.swipe(StrUtils.SCREEN_W / 2, StrUtils.SCREEN_H - 10, StrUtils.SCREEN_W / 2, 10, 100);
                count++;
            }
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",search internet fail");
            Log.d(TAG,"search internet fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.roger.wificfg");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    private void downloadApk(String apk_address,String wifiName){
        mDevice.pressHome();
        try {
            UiBase.forceStopApp("com.roger.wificfg");
            mDevice.executeShellCommand("am start -a android.intent.action.MAIN -n com.roger.wificfg/com.roger.wificfg.MainActivity --ei pid 1 --es url "+ apk_address);
            UiBase.waitObjCheck(UiBase.objSelect[2],".*%",10);
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",download apk start");
            Log.d(TAG,"start download apk");
            UiBase.waitObjCheck(UiBase.objSelect[0],"download success!",300);
            SystemClock.sleep(waitTime);
        }catch (Throwable e){
            String timeMS = UiBase.dateFormat.format(new Date(System.currentTimeMillis()));
            FileUtils.writeFile(filePath+"testWifi/result/caseLogs.csv",timeMS+","+wifiName+",download apk fail");
            Log.d(TAG,"download apk fail");
        }finally {
            mDevice.pressHome();
            try {
                UiBase.forceStopApp("com.roger.wificfg");
            } catch (IOException e) {
                e.printStackTrace();
            }
            SystemClock.sleep(waitTime * 5);
        }
    }

    @SuppressLint("DefaultLocale")
    private void wifiMonitor0(String reportName, String wifiName, String ip){
        double downloadShow;
        double uploadShow;
        WifiInfo mWifiInfo = wifiManager.getConnectionInfo();
        NetworkInfo mNetInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(mNetInfo.isConnected()){
            if(connFlag==0){
                Log.d(TAG,"conn normal");
                unConnFlag=0;
                int wifiRssi = mWifiInfo.getRssi();
                Date date1= new Date(System.currentTimeMillis());
                long downloadData1 = TrafficStats.getTotalRxBytes();
                long uploadData1 = TrafficStats.getTotalTxBytes();
                SystemClock.sleep(waitTime);
                Date date2= new Date(System.currentTimeMillis());
                long downloadData2 = TrafficStats.getTotalRxBytes();
                long uploadData2 = TrafficStats.getTotalTxBytes();
                downloadShow = (double)(downloadData2 - downloadData1) / 1024 /(double)(date2.getTime()-date1.getTime()) * 1000;
                uploadShow = (double) (uploadData2 - uploadData1) / 1024 / (double)(date2.getTime()-date1.getTime()) * 1000;
                String time = UiBase.dateFormat.format(date2);
                FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",time+",conn,"+String.format("%.2f",uploadShow)+","+
                        String.format("%.2f",downloadShow)+","+String.valueOf(wifiRssi)+", , ,");
            }else{
                Log.d(TAG,"conn again");
                connFlag=0;
                Date timeMConn = new Date(System.currentTimeMillis());
                String time =UiBase.dateFormat.format(timeMConn);
                pingIP(ip);
                FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",time+",conn again, , , ,"+baiDuP+","+routerP+", ,"+String.valueOf((timeMConn.getTime()-timeMUnConn.getTime())/1000));
            }
        }else{
            errorFlag=1;
            Log.d(TAG,"disconnect");
            if(unConnFlag==0){
                unConnTimes++;
                unConnFlag=1;
                FileUtils.takeScreenPicTo(filePath+"testWifi/pic/","disConn_"+wifiName.replaceAll(" ",""));
                timeMUnConn = new Date(System.currentTimeMillis());
                String time  = UiBase.dateFormat.format(timeMUnConn);
                pingIP(ip);
                FileUtils.writeFile(filePath+"testWifi/result/"+reportName+".csv",time+",disConn, , , ,"+baiDuP+","+routerP+","+String.valueOf(unConnTimes)+",");
            }
            connFlag=1;
            SystemClock.sleep(1000);
        }
    }

    private void wifiMonitor(final String reportName, final String wifiName, final String ip){
        isMonitor = true;
        Thread monitor =new Thread(new Runnable() {
            @Override
            public void run() {
                while(isMonitor) wifiMonitor0(reportName, wifiName, ip);
            }
        }) ;
        monitor.start();
    }

    private void UiMonitor(){
        Thread ui =new Thread(new Runnable() {
            @Override
            public void run() {
                //noinspection InfiniteLoopStatement
                while(true){
                    try {
                        UiBase.clickIfObjExist(UiBase.objSelect[2],"No, thanks|不了，谢谢|我知道了|以后再说|暂不升级|Update later");
                        SystemClock.sleep(waitTime * 10);
                    } catch (UiObjectNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }) ;
        ui.start();
    }

    private void pingIP(String ip) {
        try {
            baiDuP = mDevice.executeShellCommand("ping -c 1 -w 100 www.baidu.com");
            routerP = mDevice.executeShellCommand("ping -c 1 -w 100 " + ip);
        } catch (IOException e) {
            baiDuP=routerP="";
        }
        if(baiDuP.contains("packets transmitted")) baiDuP="pass";
        else baiDuP="fail";
        if(routerP.contains("packets transmitted")) routerP="pass";
        else routerP="fail";
    }

    private interface cases{
        void run(String wifiName);
    }

    private void addTestCase(){
        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(tencent.equals("true")) playTencentVideo(tencent_play_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(douyin.equals("true")) playDouyin(refresh_gap,douyin_play_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(douyu.equals("true")) playDouyu(douyu_play_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(weibo.equals("true")) playWeibo(refresh_gap,weibo_play_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(internet.equals("true")) searchInternet(refresh_gap,internet_search_time,wifiName);
            }
        });

        testCase.add(new cases() {
            @Override
            public void run(String wifiName) {
                if(download.equals("true")) downloadApk(apk_address,wifiName);
            }
        });
    }

    private void changePrivacy(String name){
        if(Build.VERSION.SDK_INT == 29){
            try {
                UiBase.waitClickObj(UiBase.objSelect[0],name,3);
                UiBase.waitClickObj(UiBase.objSelect[2],"隐私|Privacy",3);
                UiBase.waitClickObj(UiBase.objSelect[2],"使用设备 MAC|Use device MAC",3);
                mDevice.pressBack();
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void debug() throws Throwable {
//        Log.d(TAG,Build.PRODUCT);
//        Log.d(TAG, String.valueOf(Build.VERSION.SDK_INT));
//        logOn(Build.PRODUCT,true);
//        logOn(Build.PRODUCT,false);
//        enterWLAN();
//        changePrivacy("360WiFi-5G-SJLT");
//        if(!FileUtils.existFile(UiBase.filePath+"testWifi/result/WifiRate.csv")){
//            FileUtils.writeFile(UiBase.filePath+"testWifi/result/WifiRate.csv","DateTime,ConnState,UpRates,DownRates,RSSI,PingBaiDu,PingRouter,UnConnTimes,UnConnAllTime(s),");
//        }
//         wifiMonitor("WifiRate","test","");
//         SystemClock.sleep(waitTime * 3600 * 72 );
        //Wifi.wifi().connectWifi("Autorun_OutAP","LenovoTest12#","WPA");

//        playTencentVideo(20,"test");
//        playDouyin(5,20,"test");
//        playDouyu(20,"test");
//        playWeibo(5,20,"test");
//        searchInternet(5,20,"");
//        downloadApk("https://dldir1.qq.com/weixin/android/weixin707android1520.apk","test");

        FileUtils.writeFile(filePath+"1.txt","124");
    }




}
